package kiwi.core.handler.solr;

import kiwi.core.services.search.SolrIndexingServiceImpl;
import org.apache.http.ParseException;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.handler.component.SearchHandler;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;

/**
 * User: Thomas Kurz
 * Date: 28.02.11
 * Time: 15:14
 */
public class KiWiSolrRequestHandler extends SearchHandler {


	@Override
	public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception, ParseException, InstantiationException, IllegalAccessException {
		//rewrite request
		ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
		String q = rewriteQ(params.get("q"));
		String[] f = rewriteF(params.getParams("facet.field"));
		String[] fq = rewriteFQ(params.getParams("fq"));
		String[] fl = rewriteF(params.get("fl").split(","));
		String fls = Arrays.asList(fl).toString();
		fls = fls.length()>0 ? fls.substring(1,fls.length()-1) : fls;
		params.set("q",q);
		params.set("facet.field",f);
		params.set("fq",fq);
		params.set("fl", fls);
		req.setParams(params);
		super.handleRequestBody(req, rsp);

	}

	private String rewriteQ(String q) {
		try {
			if (q != null) {
				String[] sa = URLDecoder.decode(q,"utf-8").split(" ");
			 	StringBuffer b = new StringBuffer();
		     	for(String x : sa) {
				 int i = x.indexOf(":");
				 if(i>-1) {
				 	b.append(SolrIndexingServiceImpl.Program().getInternalName(x.substring(0, i)));
				 	b.append(x.substring(i));
				 } else {
					 b.append(x);
				 }
				b.append(" ");
			 	}
				q=b.toString();
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();//should never happen
		}
		return q;
	}

	private String[] rewriteF(String[] f) {
		if (f != null && f.length > 0) {
			for (int i = 0; i < f.length; i++) {;
				f[i] = SolrIndexingServiceImpl.Program().getInternalName(f[i]);
			}
		}
		return f;
	}

	private String[] rewriteFQ(String[] q) {
		if (q != null) {
			for(int i=0; i<q.length;i++) {
				q[i] = rewriteQ(q[i]);
			}
		}
		return q;
	}

}
